<template>
    <div style="z-index: 1000;"> <!-- style="z-index: 1000;" -->
        <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
                style="border-bottom: 1px solid #ccc" />
            <Editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml" style="height: 400px; overflow-y: hidden"
                @onCreated="handleCreated" @onChange="handleChange" @keyup.esc="unFullScreen" />
        </div>
    </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { ref, inject, onBeforeUnmount, shallowRef, nextTick } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const serverUrl = inject('serverUrl')
const editorRef = shallowRef();
const valueHtml = ref('');
const mode = 'default'
const toolbarConfig = {};
const editorConfig = { placeholder: '请输入内容...' };

const props = defineProps({
    content: {
        type: String,
        default: ""
    }
})
const emit = defineEmits(['update:content'])

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor) => {
    console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
    editor.on('unFullScreen', () => {
        editor.unFullScreen()
    })
};
const handleChange = (editor) => {
    // console.log('change:', editor.getHtml());
    emit('update:content', valueHtml.value)
};

const unFullScreen = () => {
    const editor = editorRef.value;
    if (editor.isFullScreen) {
        editor.emit('unFullScreen')
    }
}

// 渲染完成, DOM立即更新一次
nextTick(() => {
    valueHtml.value = props.content
})

// editorConfig
editorConfig.MENU_CONF = {}
editorConfig.MENU_CONF['uploadImage'] = {
    // 小于该值就插入 base64 格式（而不上传），默认为 0
    base64LimitSize: 20 * 1024, // 5kb
    server: serverUrl + '/api/_token/upload/',
    headers: {
        token: localStorage.getItem("token"),
    },
    fieldName: 'fields'
}
editorConfig.MENU_CONF['insertImage'] = {
    parseImageSrc: (src) => {
        if (src.indexOf('http') !== 0 && src.indexOf('base64') == -1) {
            return `${serverUrl}/${src}`
        }
        return src
    }
}
// toolbarConfig
toolbarConfig.excludeKeys = [
    'uploadVideo'
]
</script>

<style lang="scss" scoped></style>